package com.it.flowable.service.leave.bpm;

import com.alibaba.fastjson2.JSON;
import com.it.flowable.common.constants.BpmLeaveConstant;
import com.it.flowable.common.vo.leave.LeaveBpmParamVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 请假流程各流程提交主方法
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class BpmLeaveBm {

    @Resource
    private BpmLeaveDao bpmLeaveDao;
    @Resource
    private BpmLeaveStartProcessServiceReImpl bpmProcessServiceRe;
    @Resource
    private BpmLeaveTaskService bpmLeaveTaskService;

    /**
     * 开启请假申请流程
     */
    public String startApplyProcess(Map<String, Object> leaveBpmParamMap) throws Exception {
        log.info("初次请假申请工作流参数>>> " + JSON.toJSONString(leaveBpmParamMap));
        String processKey = BpmLeaveConstant.LEAVE_PROCESS_KEY;
        // 参数获取
        LeaveBpmParamVO leaveBpmParamVO = JSON.to(LeaveBpmParamVO.class,
                JSON.toJSONString(leaveBpmParamMap.get("LeaveBpmParamVO")));

        if (StringUtils.isEmpty(processKey)) {
            throw new Exception("通过processKey启动流程失败：BpmLeaveBm.startApplyProcess，processKey流程主键值为空，请联系管理员");
        }

        List<Map<String, Object>> resultList = bpmProcessServiceRe.startProcess(processKey, leaveBpmParamMap);
        if (CollectionUtils.isNotEmpty(resultList)) {
            Map<String, Object> map = resultList.get(0);
            String cTaskId = MapUtils.getString(map, "cTaskId");
            // 接收任务
            bpmLeaveTaskService.acceptTask(cTaskId, leaveBpmParamVO.getCAppCde());
            // 完成任务
            // todo: 这里完成请假申请流程的同时，会自动触发下一流程 一级审批的流程创建,所以将其放到主流程中去处理
//            bpmLeaveTaskService.completeTask(cTaskId, leaveBpmParamMap);
            return cTaskId;
        } else {
            throw new Exception("启动流程失败：BpmLeaveBm.startApplyProcess，请联系管理员");
        }
    }

    public void submitTask(Map<String, Object> leaveBpmParamMap) throws Exception {
        LeaveBpmParamVO bpmParamVO = JSON.to(LeaveBpmParamVO.class,
                JSON.toJSONString(leaveBpmParamMap.get("LeaveBpmParamVO")));
        String taskId = bpmParamVO.getCTaskId();
        log.info("传递工作流信息数据：流程id：" + taskId + " 基本信息：" + JSON.toJSONString(leaveBpmParamMap));
        bpmLeaveTaskService.completeTask(taskId, leaveBpmParamMap);
    }

}
